package com.wz.project.api.sap.sapconn;

import com.sap.conn.jco.*;
import com.sap.conn.jco.ext.DestinationDataProvider;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.project.api.sap.domain.InputData;
import com.wz.project.sap.DN_POST_DN.domain.ZflWmsDnPostDn;
import com.wz.project.sap.POST_TMDATA_SERIAL.domain.YppRfcPostTmdataSerial;
import com.wz.project.sap.POST_TMDATA_TMINTERF.domain.YppRfcPostTmdataTminterf;
import com.wz.project.sap.PYPK.domain.ZflWmsPyPk;
import com.wz.project.sap.STOCK_TRANSFER.domain.ZflWmsStockTransferHeader;
import com.wz.project.sap.STOCK_TRANSFER.domain.ZflWmsStockTransferItem;
import com.wz.project.sap.STOCK_TRANSFER.domain.ZflWmsStockTransferSeri;
import com.wz.project.sap.STOCK_TRANSFER.mapper.ZflWmsStockTransferHeaderMapper;
import com.wz.project.util.InterfaceLogUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SAPConn {

    private static final String ABAP_AS_POOLED = "ABAP_AS_WITH_POOL";

    static{
        Properties connectProperties = new Properties();
        connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "192.168.3.182");//SAP正式服务器
//        connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "192.168.3.78");//SAP测试服务器
        connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR,  "00");        //系统编号
        connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "800");       //SAP集团
        connectProperties.setProperty(DestinationDataProvider.JCO_USER,   "XALK_RFC");  //SAP用户名
        connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "xian@2023");     //密码
        connectProperties.setProperty(DestinationDataProvider.JCO_LANG,   "zh");        //登录语言
        connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");  //最大连接数
        connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");     //最大连接线程

        createDataFile(ABAP_AS_POOLED, "jcoDestination", connectProperties);
    }

    private static void createDataFile(String name, String suffix, Properties properties){
        File cfg = new File(name+"."+suffix);
        if(cfg.exists()){
            cfg.deleteOnExit();
        }
        try{
            FileOutputStream fos = new FileOutputStream(cfg, false);
            properties.store(fos, "for tests only !");
            fos.close();
        }catch (Exception e){
            System.err.println("Create Data file fault, error msg: " + e.toString());
            throw new RuntimeException("Unable to create the destination file " + cfg.getName(), e);
        }
    }

    public static JCoDestination connect(){
        JCoDestination destination =null;
        try {
            destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
        } catch (JCoException e) {
            System.err.println("Connect SAP fault, error msg: " + e.toString());
        }
        return destination;
    }

    public static AjaxResult getTableXml(String name, InputData...inputData){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息

        try {

            function = destination.getRepository().getFunction(name);

            JCoParameterList input = function.getImportParameterList();
            for (InputData i:inputData){

                input.setValue(i.getKey(),i.getValue());
            }
            function.execute(destination);
            result = function.getExportParameterList().getString("EV_TYPE");//调用接口返回状态
            message = function.getExportParameterList().getString("EV_MESSAGE");//调用接口返回信息\
            if (result.equals("E")) {
                InterfaceLogUtil.setLog(name,inputData.toString(),result+","+message);
                return AjaxResult.error(message);
            } else {
                JCoParameterList teleport = function.getTableParameterList();
                String msg = teleport.toXML();
                InterfaceLogUtil.setLog(name,inputData.toString(),result+","+message);
                return AjaxResult.success(msg);
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            return AjaxResult.error("SAP接口连接异常");
        }
    }

    public static AjaxResult getProListXml(String name, InputData...inputData){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息
        String data="";
        try {
            function = destination.getRepository().getFunction(name);
            JCoParameterList input = function.getImportParameterList();
            for (InputData i:inputData){
                input.setValue(i.getKey(),i.getValue());
                data=data + i.getKey()+":"+i.getValue()+";";
            }
            function.execute(destination);
            result = function.getExportParameterList().getString("PC_O_FLAG");//调用接口返回状态
            message = function.getExportParameterList().getString("PC_O_MESSAGE");//调用接口返回信息\
            if (!result.equals("1")) {
                InterfaceLogUtil.setLog(name,data,result+","+message);
                return AjaxResult.error(message);
            } else {
                JCoParameterList teleport = function.getTableParameterList();
                String msg = teleport.toXML();
                InterfaceLogUtil.setLog(name,data,result+","+message);
                return AjaxResult.success(msg);
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            return AjaxResult.error("SAP接口连接异常");
        }
    }


    public static AjaxResult getTMADATAXml(YppRfcPostTmdataTminterf tminterf, YppRfcPostTmdataSerial serial){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息
        String sapmdn="";//生成的SAP单据唯一标识(年度+流水号)
        try {
            function = destination.getRepository().getFunction("YPP_RFC_POST_TMDATA");
            if(function == null)
                throw new RuntimeException("ZFM_FI_TAXPLATFORM_PRICE not found in SAP.");
            //获取传入表参数SN_ITEM
            JCoTable SN_ITEM = function.getImportParameterList().getTable("PIT_I_TMINTERF");
            SN_ITEM.appendRow();//增加一行
            //给表参数中的字段赋值

            SN_ITEM.setValue("MANDT", tminterf.getMANDT());
            SN_ITEM.setValue("ZDOCNO", tminterf.getZDOCNO());
            SN_ITEM.setValue("POSNR", tminterf.getPOSNR());
            SN_ITEM.setValue("ZSAPDOCNO", tminterf.getZSAPDOCNO());
            SN_ITEM.setValue("ZDOCTP", tminterf.getZDOCTP());
            SN_ITEM.setValue("ZBUSTP", tminterf.getZBUSTP());
            SN_ITEM.setValue("BUDAT", tminterf.getBUDAT());
            SN_ITEM.setValue("MATNR", tminterf.getMATNR());
            SN_ITEM.setValue("ERFMG", tminterf.getERFMG());
            SN_ITEM.setValue("ERFME", tminterf.getERFME());
            SN_ITEM.setValue("WERKS", tminterf.getWERKS());
            SN_ITEM.setValue("ZLOC_I", tminterf.getZLOC_I());
            SN_ITEM.setValue("ZOPRTER", tminterf.getZOPRTER());
            SN_ITEM.setValue("ZPSTDT", tminterf.getZPSTDT());
            SN_ITEM.setValue("ZPSTTM", tminterf.getZPSTTM());
            SN_ITEM.setValue("BATCH", tminterf.getBATCH());

            JCoTable SERIAL = function.getImportParameterList().getTable("PIT_I_SERIAL");
            SERIAL.appendRow();//增加一行
            SERIAL.setValue("MANDT",serial.getMANDT());
            SERIAL.setValue("SERIALNO",serial.getSERIALNO());
            SERIAL.setValue("MATDOC_ITM",serial.getMATDOC_ITM());
            SERIAL.setValue("MAPAR",serial.getMAPAR());
            SERIAL.setValue("MATNR",serial.getMATNR());


            function.execute(destination);
            result = function.getExportParameterList().getString("PC_O_FLAG");//调用接口返回状态
            message = function.getExportParameterList().getString("PC_O_MESSAGE");//调用接口返回信息\
            sapmdn=function.getExportParameterList().getString("PC_O_SAPMDN");//生成的SAP单据唯一标识(年度+流水号)
            if (!result.equals("1")) {
                InterfaceLogUtil.setLog("YPP_RFC_POST_TMDATA",tminterf.toString(),result+","+message);
                return AjaxResult.error(message);
            } else {
                JCoParameterList teleport = function.getTableParameterList();
                String msg = teleport.toXML();
                InterfaceLogUtil.setLog("YPP_RFC_POST_TMDATA",tminterf.toString(),result+","+message);
                return AjaxResult.success(msg);
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            return AjaxResult.error("SAP接口连接异常");
        }
    }


    public static ZflWmsStockTransferHeader getTransferXml(List<ZflWmsStockTransferHeader> list1,
                                            List<ZflWmsStockTransferItem> list2,
                                            List<ZflWmsStockTransferSeri> list3){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息
        ZflWmsStockTransferHeader header = list1.get(0);
        try {
            function = destination.getRepository().getFunction("ZFL_WMS_STOCK_TRANSFER");
            if(function == null)
                throw new RuntimeException("ZFM_FI_TAXPLATFORM_PRICE not found in SAP.");
            //获取传入表参数SN_ITEM
            JCoParameterList input = function.getImportParameterList();
            JCoStructure SN_ITEM = input.getStructure("IS_HEADER");
            //SN_ITEM.appendRow();//增加一行
            //给表参数中的字段赋值
            SN_ITEM.setValue("BUDAT", header.getBUDAT());
            SN_ITEM.setValue("REF_DOC_NO", header.getRefDocNo());
            SN_ITEM.setValue("HEADER_TXT", header.getHeaderTxt());
            SN_ITEM.setValue("BWART",header.getBWART());

            JCoTable ITEM = function.getTableParameterList().getTable("IT_ITEM");
            for(int i=0;i<list2.size();i++) {
                ZflWmsStockTransferItem item = list2.get(i);
                ITEM.appendRow();//增加一行
                ITEM.setValue("ZEILE", item.getZEILE());
                ITEM.setValue("WERKS", item.getWERKS());
                ITEM.setValue("WERKS_TO", item.getWerksTo());
                ITEM.setValue("MATNR", item.getMATNR());
                ITEM.setValue("MATNR_TO", item.getMatnrTo());
                ITEM.setValue("LGORT", item.getLGORT());
                ITEM.setValue("LGORT_TO", item.getLgortTo());
                ITEM.setValue("ERFMG", item.getERFMG());
                ITEM.setValue("ERFME", item.getERFME());
                ITEM.setValue("CHARG", item.getCHARG());
                ITEM.setValue("CHARG_TO", item.getChargTo());
                ITEM.setValue("AUFNR", item.getAUFNR());
                ITEM.setValue("RSNUM", item.getRSNUM());
                ITEM.setValue("RSPOS", item.getRSPOS());
                ITEM.setValue("KDAUF", item.getKDAUF());
                ITEM.setValue("KDPOS", item.getKDPOS());
                ITEM.setValue("MAT_KDAUF", item.getMatKdauf());
                ITEM.setValue("MAT_KDPOS", item.getMatKdpos());
            }
            JCoTable SERIAL = function.getTableParameterList().getTable("IT_SERI");
            for(int j=0;j<list3.size();j++) {
                ZflWmsStockTransferSeri seri = list3.get(j);
                SERIAL.appendRow();
                SERIAL.setValue("ZEILE", seri.getZEILE());
                SERIAL.setValue("SERNR", seri.getSERNR());
            }
            function.execute(destination);
            result = function.getExportParameterList().getString("EV_TYPE");//调用接口返回状态
            message = function.getExportParameterList().getString("EV_MESSAGE");//调用接口返回信息\
            if (result.equals("E")) {

                header.setEvType(result);
                header.setEvMessage(message);

                InterfaceLogUtil.setLog("ZFL_WMS_STOCK_TRANSFER",header.toString(),message);

                return header;
            } else {
//                JCoParameterList teleport = function.getTableParameterList();
//                String msg = teleport.toXML();
                //修改WMS库存调拨标记  返回消息类型+返回消息
                header.setEvType(result);
                header.setEvMessage(message);
                InterfaceLogUtil.setLog("ZFL_WMS_STOCK_TRANSFER",header.toString(),"成功");

                return header;
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            header.setEvType("E");
            header.setEvMessage("SAP接口连接异常");
            return header;
        }
    }

    public static AjaxResult getPYPKXml(ZflWmsPyPk zflWmsPyPk){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息
        try {
            function = destination.getRepository().getFunction("ZFL_WMS_PY_PK");
            if(function == null)
                throw new RuntimeException("ZFM_FI_TAXPLATFORM_PRICE not found in SAP.");


            //获取传入表参数SN_ITEM
            JCoTable SN_ITEM = function.getTableParameterList().getTable("IT_ODN");
            SN_ITEM.appendRow();//增加一行
            //给表参数中的字段赋值

            SN_ITEM.setValue("BLDAT", zflWmsPyPk.getBLDAT());
            SN_ITEM.setValue("BUDAT", zflWmsPyPk.getBUDAT());
            SN_ITEM.setValue("BWART", zflWmsPyPk.getBWART());
            SN_ITEM.setValue("WERKS",zflWmsPyPk.getWERKS());
            SN_ITEM.setValue("LGORT",zflWmsPyPk.getLGORT());
            SN_ITEM.setValue("MATNR",zflWmsPyPk.getMATNR());
            SN_ITEM.setValue("ERFMG",zflWmsPyPk.getERFMG());
            SN_ITEM.setValue("ERFME",zflWmsPyPk.getERFME());
            SN_ITEM.setValue("CHARG",zflWmsPyPk.getCHARG());


            function.execute(destination);
            result = function.getExportParameterList().getString("EV_TYPE");//调用接口返回状态
            message = function.getExportParameterList().getString("EV_MESSAGE");//调用接口返回信息\
            if (result.equals("E")) {
                return AjaxResult.error(message);
            } else {
//                JCoParameterList teleport = function.getTableParameterList();
//                String msg = teleport.toXML();
                return AjaxResult.success(message);
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            return AjaxResult.error("SAP接口连接异常");
        }
    }

    public static AjaxResult getDNPOSTXml(List<ZflWmsDnPostDn> dn){
        JCoFunction function = null;
        JCoDestination destination = SAPConn.connect();
        String result = "";//调用接口返回状态
        String message = "";//调用接口返回信息
        try {
            function = destination.getRepository().getFunction("ZFL_WMS_DN_POST");
            if(function == null)
                throw new RuntimeException("ZFM_FI_TAXPLATFORM_PRICE not found in SAP.");

            JCoParameterList input = function.getImportParameterList();
            input.setValue("IV_VBELN",dn.get(0).getVBELN());
            input.setValue("IV_BUDAT",new SimpleDateFormat("yyyyMMdd").format(new Date()));


            //获取传入表参数SN_ITEM
            JCoTable SN_ITEM = function.getTableParameterList().getTable("IT_DN");
            JCoTable SERIAL = function.getTableParameterList().getTable("IT_SERIAL");
            for(int i=0;i<dn.size();i++){
                SN_ITEM.appendRow();//增加一行
                //给表参数中的字段赋值

                SN_ITEM.setValue("ZEILE",dn.get(i).getZEILE());
                SN_ITEM.setValue("VBELN",dn.get(i).getVBELN());
                SN_ITEM.setValue("POSNR",dn.get(i).getPOSNR());
                SN_ITEM.setValue("MATNR",dn.get(i).getMATNR());
                SN_ITEM.setValue("LFIMG",dn.get(i).getLFIMG());
                SN_ITEM.setValue("PIKMG",dn.get(i).getPIKMG());
                SN_ITEM.setValue("WERKS",dn.get(i).getWERKS());
                SN_ITEM.setValue("LGORT",dn.get(i).getLGORT());
                SN_ITEM.setValue("CHARG",dn.get(i).getCHARG());
                SN_ITEM.setValue("VRKME",dn.get(i).getVRKME());

                SERIAL.appendRow();
                SERIAL.setValue("ZEILE",dn.get(i).getZEILE());
                SERIAL.setValue("SERNR",dn.get(i).getSERNR());

            }





            function.execute(destination);
            result = function.getExportParameterList().getString("EV_TYPE");//调用接口返回状态
            message = function.getExportParameterList().getString("EV_MESSAGE");//调用接口返回信息\
            if (result.equals("E")) {
                InterfaceLogUtil.setLog("ZFL_WMS_DN_POST",dn.toString(),result+","+message);
                return AjaxResult.error(message);
            } else {
                JCoParameterList teleport = function.getTableParameterList();
                String msg = teleport.toXML();
                InterfaceLogUtil.setLog("ZFL_WMS_DN_POST",dn.toString(),result+","+message);
                return AjaxResult.success(msg);
            }
        } catch (JCoException e) {
//            e.printStackTrace();
            return AjaxResult.error("SAP接口连接异常");
        }
    }
}
